//
//  DJregistVIew.m
//  掌中会议通
//
//  Created by wanghy on 15/12/14.
//  Copyright © 2015年 wanghy. All rights reserved.
//
#import "EaseMob.h"
#import "DJregistVIew.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+Ex.h"
#import <SMS_SDK/SMSSDK.h>
#define Keypass @"passDict"


@interface DJregistVIew ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *getVerificationBtn;
//手机号
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
//验证码
@property (weak, nonatomic) IBOutlet UITextField *VerificationNum;
//密码
@property (weak, nonatomic) IBOutlet UITextField *passTextfled;
//确认密码
@property (weak, nonatomic) IBOutlet UITextField *confirmPass;
//复选框
@property (weak, nonatomic) IBOutlet UIButton *fuXuanKuang;
//使用协议
@property (weak, nonatomic) IBOutlet UIButton *useProtocol;
//注册按钮
@property (weak, nonatomic) IBOutlet UIButton *registBtn;
//点击获取验证码后的秒数
@property(nonatomic,assign)int second;
//用于改变按钮数字的定时器
@property(nonatomic,strong)NSTimer *djTimer;

//存放密码的数组
//@property(nonatomic,strong)NSMutableDictionary* passDict;

@end

@implementation DJregistVIew

#pragma mark - 注册按钮的点击事件



- (IBAction)didClickRsgistBtn:(id)sender {
    
    
    
    
    
    
    if([self.VerificationNum.text isEqualToString:@""]){
        
        [MBProgressHUD showError:@"请先获取验证码再注册"];
        
    }else{
        if(!([self.passTextfled.text isEqualToString:self.confirmPass.text]) ){
            [MBProgressHUD showError:@"两次密码输入不一致"];
            return;
        }
        
        if([self.passTextfled.text isEqualToString: @""]||[self.confirmPass.text isEqualToString:@""]){
            
            [MBProgressHUD showError:@"请完善密码信息"];
            
            
        }else{
            
            
            
            
            
            
            [SMSSDK commitVerificationCode:self.VerificationNum.text phoneNumber:self.phoneNumber.text zone:@"86" result:^(NSError *error) {
                
                NSLog(@"-----%@",error);
                if (error==nil) {
                    
                    
                    //在这里写验证成功之后的代码
                    
                    [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:self.phoneNumber.text password:self.passTextfled.text withCompletion:^(NSString *username, NSString *password, EMError *error) {
                        if (!error) {
                            [MBProgressHUD showSuccess:@"注册成功"];
                        }
                        
                        else{
                            [MBProgressHUD showSuccess:@"该账号已经存在"];
                            
                        }
                    } onQueue:nil];
                    
                    
                    
                    
                    
                    
                    //                获取保存密码的字典
                    NSMutableDictionary * oldPassDict = [[NSUserDefaults standardUserDefaults]objectForKey:Keypass];
                    //                用当前的text里面的账号和密码创建新字典
                    NSMutableDictionary * newPassDict = [NSMutableDictionary dictionaryWithObject:self.passTextfled.text forKey:self.phoneNumber.text];
                    //                拼接两个字典
                    [newPassDict addEntriesFromDictionary:oldPassDict];
                    //                存到沙盒
                    [[NSUserDefaults standardUserDefaults]setObject:newPassDict forKey:Keypass];
                    
                    NSLog(@"%@",newPassDict);
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        //                    执行block，跳转控制器
                        NSAssert(self.dismissBlock, @"block必须存在");
                        
                        self.dismissBlock();
                    });
                    
                    //
                    
                    
                }else {
                    [MBProgressHUD showError:@"验证码错误"];
                    
                }
                
            }];
            
        }
    }
}

#pragma mark - 点击获取验证码的按钮

- (IBAction)didClickGetConfirmpass:(id)sender {
    
    
    //    验证是不是手机号的正则表达式
    NSString* pattern = @"^[1][345678][0-9]{9}$";
    NSRegularExpression* regular = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    
    NSArray* allresult = [regular matchesInString:self.phoneNumber.text options:NSMatchingReportCompletion range:NSMakeRange(0, self.phoneNumber.text.length)];
    
    //    如果没有输入手机号
    if ([self.phoneNumber.text isEqualToString:@""]) {
        
        //        NSLog(@"手机号不能为空");
        [MBProgressHUD showError:@"亲，手机号不能为空"];
    }else if (allresult.count == 0) {
        [MBProgressHUD showError:@"亲，请输入正确的手机号"];
        //         NSLog(@"请输入正确的手机号，只支持国内");
    }
    //    发送验证码
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phoneNumber.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
        if (error==nil) {
            [MBProgressHUD showSuccess:@"发送成功请注意查收" ];
            
            //            按钮读秒的方法
            [self regitBtnDongHua];
            self.getVerificationBtn.enabled = NO;
        }
    }];
    
    
    
}

//判断是否已经注册
-(void)isRegist{
    NSDictionary * passDict =     [[NSUserDefaults standardUserDefaults]objectForKey:Keypass];
    if ([passDict objectForKey:self.phoneNumber.text]) {
        
        [ MBProgressHUD showError:@"该手机号已经注册"];
        self.phoneNumber.text = @"";
        [self.phoneNumber becomeFirstResponder];
        
    }
    
}

//判断密码长度
-(void)panDuanChangDu{
    
    if (self.passTextfled.text.length < 6||self.passTextfled.text.length > 16) {
        [ MBProgressHUD showError:@"密码长度不合法"];
    }
}


#pragma mark -awakeFromNib

-(void)awakeFromNib{
    [self.phoneNumber becomeFirstResponder];
    
    
    //    [self.phoneNumber addTarget:self action:@selector(isRegist) forControlEvents:UIControlEventEditingDidEnd];
    
    [self.passTextfled addTarget:self action:@selector( panDuanChangDu) forControlEvents:UIControlEventEditingDidEnd];
}


#pragma mark - 获取验证码按钮的动画方法

-(void)regitBtnDongHua{
    
    //    1.更改button的文字
    
    self.second = 60;
    
    //    参数：1.时间间隔。2.对象 3.要执行的方法   4.向方法传递的参数。   5.是否重复。
    NSTimer * timer = [NSTimer timerWithTimeInterval:1 target:self
                                            selector:@selector(run) userInfo:nil repeats:YES];
    
    self.djTimer = timer;
    //    奔跑模式
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
}

-(void)run{
    
    if (self.second >0) {
        self.second--;
        NSLog(@"%d",self.second);
        NSString * str = [NSString stringWithFormat:@"%d",self.second];
        [self.getVerificationBtn setTitle:str forState:UIControlStateNormal];
    }else{
        
        [self.getVerificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.djTimer invalidate];
        self.getVerificationBtn.enabled = YES;
        
        
        
    }
    
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self endEditing:YES];
    
}


@end
